/**
 * 
 */
package com.iknight.mgr.core.shiro;

import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import com.iknight.mgr.api.RoleService;
import com.iknight.mgr.model.RoleModel;

/**
 * @author Jeryzym
 *
 */
public class MgrEhcacheRealm extends AuthorizingRealm {
	private final Logger logger = LogManager.getLogger(getClass());

	@Autowired
	private RoleService<RoleModel, String> roleService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache
	 * .shiro.subject.PrincipalCollection)
	 */
	/**
	 * @description 用户权限验证
	 */
	@SuppressWarnings("unchecked")
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		Subject subject = SecurityUtils.getSubject();
		if (subject == null) {
			return null;
		}

		Session session = subject.getSession(false);
		if (session == null) {
			return null;
		}

		// Map<String, String> user = (Map<String, String>)
		// principals.getPrimaryPrincipal();
		String curUser = (String) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		/*
		 * load Permissions
		 */
		List<Map> perms = roleService.getPermsByUsername(curUser);
		if (perms != null) {
			for (Map<String, String> perm : perms) {
				info.addStringPermission(perm.get("perm_code"));
			}
		}

		/*
		 * load Roles
		 */
		List<Map> roles = roleService.getRolesByUsername(curUser);
		if (roles != null) {
			for (Map<String, String> role : roles) {
				info.addRole(role.get("role_code"));
				logger.debug(role.get("role_code"));
			}
		}
		return info;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.
	 * apache.shiro.authc.AuthenticationToken)
	 */
	/**
	 * @description 用户登录验证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		MgrToken mgrToken = (MgrToken) token;
		MgrAuthInfo info = new MgrAuthInfo(mgrToken.getPrincipal(), mgrToken.getCredentials(), getName(),
				mgrToken.getUserId());
		return info;
	}
}
